package com.xujiang.myblog.ui;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.xujiang.common.ui.CPBaseActivity;
import com.xujiang.myblog.R;
import com.xujiang.myblog.entity.TabEntity;
import com.xujiang.myblog.model.AccessToken;
import com.xujiang.myblog.model.HeadPicture;
import com.xujiang.myblog.network.retrofit.MRetrifit;
import com.xujiang.myblog.tools.ImageUtils;
import com.xujiang.myblog.util.CPProgressDialog;
import com.xujiang.myblog.util.Callback;
import com.xujiang.myblog.util.Callback2;
import com.xujiang.myblog.util.L;
import com.xujiang.myblog.util.TakeImagesHelper;
import com.xujiang.myblog.util.UIUtils;
import com.xujiang.myblog.util.Utils;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscription;

public class AddBlogActivity extends CPBaseActivity {
    public static final String TAG = AddBlogActivity.class.getSimpleName();
    @BindView(R.id.iv_cover_activityaddblog)
    ImageView ivCoverActivityaddblog;
    @BindView(R.id.tab_addblogactivity)
    CommonTabLayout tabAddblogactivity;

    TakeImagesHelper mTakeImagesHelper;
    @BindView(R.id.content_addblogactivity)
    EditText contentAddblogactivity;

    CPProgressDialog mProgressDialog;
    Subscription uploadPictureSubscription;

    private String[] mTitles = { "", "", "", "", "" };
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private int[] mIconUnselectIds = {
            R.drawable.compose_toolbar_picture, R.drawable.compose_toolbar_form,
            R.drawable.compose_toolbar_link, R.drawable.compose_toolbar_lead,
            R.drawable.compose_toolbar_more };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_blog);
        ButterKnife.bind(this);
        initToolbar();

        mProgressDialog = new CPProgressDialog(AddBlogActivity.this);
        mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                Utils.unsubscribe(uploadPictureSubscription);
            }
        });

        mTakeImagesHelper = TakeImagesHelper.with(this);

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconUnselectIds[i], mIconUnselectIds[i]));
        }

        tabAddblogactivity.setTabData(mTabEntities);

        tabAddblogactivity.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                //SpannableString和ImageSpan
                switch (position) {
                    case 0:
                        mTakeImagesHelper.showTakeImageDialog(new Callback2.EmptyCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                L.i(TAG, s);
                                L.getToast().showLog(AddBlogActivity.this, s);
                                Bitmap bitmap = ImageUtils.getLoacalBitmap(s); //从本地取图片
                                upload(s, bitmap);
                            }

                            @Override
                            public void onError(Throwable e) {
                                L.getToast().e(TAG, AddBlogActivity.this, e);
                            }

                        });

                        break;
                }

            }

            @Override
            public void onTabReselect(int position) {
                onTabSelect(position);
            }
        });

        contentAddblogactivity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    tabAddblogactivity.setVisibility(View.GONE);
                }
            }
        });

        contentAddblogactivity.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                tabAddblogactivity.setVisibility(View.VISIBLE);
                return false;
            }
        });

    }

    /**
     * 图片上传
     */
    private void upload(String file, Bitmap bitmap) {
        uploadPictureSubscription = MRetrifit.get()
                .uploadfile(new File(file), new Callback.EmptyCallback<AccessToken<HeadPicture>>() {
                    @Override
                    public void onPreExecute() {
                        UIUtils.showDialog(mProgressDialog);
                    }

                    @Override
                    public void onPostExecute() {
                        UIUtils.dismissDialog(mProgressDialog);
                    }

                    @Override
                    public void onSuccess(AccessToken<HeadPicture> headPictureAccessToken) {
                        super.onSuccess(headPictureAccessToken);
                        String headpictureurl = headPictureAccessToken.getLisTt().get(0).getHeadpictureurl();
                        // 根据Bitmap对象创建ImageSpan对象
                        ImageSpan imageSpan = new ImageSpan(AddBlogActivity.this, bitmap);
                        // 创建一个SpannableString对象，以便插入用ImageSpan对象封装的图像
                        String tempUrl =
                                "<img src='' url='' style='display: none;'><img alt='加载中...' title='图片加载中...' src="
                                        + headpictureurl + ">";

                        SpannableString spannableString = new SpannableString(tempUrl);
                        // 用ImageSpan对象替换你指定的字符串
                        spannableString.setSpan(imageSpan, 0, tempUrl.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        // 将选择的图片追加到EditText中光标所在位置
                        int index = contentAddblogactivity.getSelectionStart(); // 获取光标所在位置
                        Editable edit_text = contentAddblogactivity.getText(); //EditText View的getText直接返回的就是 Editable而 TextView则是getEditableText才返回 Editable。
                        if (index < 0 || index >= edit_text.length()) {
                            edit_text.append("\n");
                            edit_text.append(spannableString);
                            edit_text.append("\n");

                        } else {
                            edit_text.append("\n");
                            index = contentAddblogactivity.getSelectionStart();
                            edit_text.insert(index, spannableString);
                            edit_text.append("\n");
                            contentAddblogactivity.setSelection(edit_text.length());
                        }
                        System.out.println("插入的图片：" + spannableString.toString());

                        //                Glide.with(AddBlogActivity.this).load(headpictureurl).bitmapTransform(new CropCircleTransformation(AddBlogActivity.this)).into(view);
                    }

                    @Override
                    public void onError(Exception e) {
                        e.printStackTrace();
                    }
                });
    }

    /**
     * Toolbar的初始化
     */
    private void initToolbar() {
        initToolBar();
        getBaseActionBar().setDisplayHomeAsUpEnabled(false);
        setTitle("编辑我的Blog");
        setToolBarleft(R.drawable.msp_input_delete);
        setToolBarRight(R.drawable.alipay_msp_gou);
        getToolbar().setBackgroundColor(getResources().getColor(R.color.white));

    }

    /**
     * 标题图片设置
     */
    @OnClick(R.id.iv_cover_activityaddblog)
    public void onClick() {
        mTakeImagesHelper.showTakeImageDialog(new Callback2.EmptyCallback<String>() {
            @Override
            public void onSuccess(String s) {
                L.i(TAG, s);
                L.getToast().showLog(AddBlogActivity.this, s);
                Bitmap bitmap = ImageUtils.getLoacalBitmap(s); //从本地取图片
                ivCoverActivityaddblog.setImageBitmap(bitmap);    //设置Bitmap
            }

            @Override
            public void onError(Throwable e) {
                L.getToast().e(TAG, AddBlogActivity.this, e);
            }

        });

    }

}
